<template>
	<view :data-theme="theme" class="container">
		<!-- 回显资质数据 -->
		<echo v-if="echoShow" :merchantData="merchantData" @send-data="handleData"></echo>
		<!-- 跟新保存信息 -->
		<view class="one" v-else="echoShow">
			<view class="scrollHeight">
				<view class="bian">
					<view class="title"><span></span>营业执照<text class="text-gray">（请上传最新中国大陆营业执照正面照）</text></view>

					<u--form labelPosition="left" :model="merchantData" :rules="rules" ref="licenseForm"
						label-width="140px">

						<u-form-item borderBottom>
							<view class="yyzz">

								<view class="license">
									<u-upload style="" :fileList="fileList3" @afterRead="afterRead" @delete="deletePic"
										width="140" height="85" name="3" multiple :maxCount="1">
										<image v-if="!licenseImage" src="../../imgs/license.png" mode="heightFix"
											style="width: 140px;height: 85px;">
										</image>
										<image v-else :src="licenseImage" mode="heightFix"
											style="width: 140px;height: 85px;">
										</image>
									</u-upload>
								</view>
								<view>营业执照</view>
							</view>
						</u-form-item>
						<u-form-item label="公司类型" prop="isLegalName" borderBottom @click="isLegalShow = true;">
							<u--input v-model="merchantData.isLegalName" disabled disabledColor="#ffffff"
								placeholder="请选择公司类型" border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>

						</u-form-item>
						<u-form-item label="统一社会信用代码" prop="legalCardNum" borderBottom>
							<u--input v-model="merchantData.legalCardNum" disabledColor="#ffffff"
								placeholder="请输入统一社会信用代码" border="none"></u--input>

						</u-form-item>
						<u-form-item label="单位名称" prop="legalName" borderBottom>
							<u--input v-model="merchantData.legalName" disabledColor="#ffffff" placeholder="请输入单位名称"
								border="none"></u--input>

						</u-form-item>
						<u-form-item label="注册地址" prop="legalRegisterAddress" borderBottom>
							<u--input v-model="merchantData.legalRegisterAddress" disabledColor="#ffffff"
								placeholder="请输入注册地址" border="none"></u--input>

						</u-form-item>
					</u--form>
					<u-action-sheet :show="isLegalShow" :actions="isLegalList" title="请选择公司类型"
						@close="isLegalShow = false" @select="isLegalListSelect">
					</u-action-sheet>


					<view class="indate">
						<view class="header">执照有效期</view>
						<view class="indateList">
							<view class="indateItem" :class='licenseIndex === 0?"selectStyle":""'
								@click="licenseClick(0,licenseArray[0])">
								<view class="itemLeft">{{licenseArray[0].name}}</view>
								<view class="itemRight">{{licenseArray[0].time}}</view>
							</view>

							<view class="indateItem" :class='licenseIndex === 1?"selectStyle":""'
								@click="licenseClick(1,licenseArray[1])">
								<view class="itemLeft">{{licenseArray[1].name}}</view>
								<uni-datetime-picker type="daterange" :start="formatDate(startDate)"
									:end="formatDate(endDate)" rangeSeparator="至" @change="confirm"
									v-model="legalValidity">{{licenseArray[1].time}}</uni-datetime-picker>
							</view>
						</view>
					</view>


				</view>
			</view>

			<view class="btn flex flex-direction bottomStyle">
				<view class="bg_color"
					style="color: white;border-radius: 50px; width: 100%;height: 35px;text-align: center;line-height: 35px;font-size: 20px;"
					@click="updateClick">更新保存</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		setThemeColor
	} from '../../utils/setTheme';
	import echo from "./components/echo/echo.vue"
	import {
		getBasicApi,
		basicUpdateApi
	} from "@/api/merchant.js"

	let app = getApp();
	export default {
		components: {
			echo,
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				basicMessage: {},
				echoShow: false,
				// 编辑

				merchantData: {
					qualificationPicture: '', //资质图片不能为空
					isLegal: '', //商户标识不能为空  户标识：1-机构、0-个人
					isLegalName: '',
					legalName: '', //机构名称不能为空
					legalCardNum: '', //统一社会信用代码不能为空
					legalRegisterAddress: '', //注册地址不能为空
					legalValidity: "", //有效期
					legalValidityType: '', // 有效期类型
				},

				isLegalShow: false,
				fileList3: [],
				licenseImage: '', // 执照图片
				rules: {
					legalName: [{
						required: true,
						message: '请输入机构名称',
						trigger: ['blur', 'change']
					}],
					legalCardNum: [{
						required: true,
						message: '请输入统一社会信用代码',
						trigger: ['blur', 'change']
					}],
					legalRegisterAddress: [{
						required: true,
						message: '请输入注册地址',
						trigger: ['blur', 'change']
					}],
					isLegalName: [{
						required: true,
						message: '请选择商户标识',
						trigger: ['blur', 'change']
					}],

				},
				// 执照有效期信息
				licenseArray: [{
						name: '长期有效',
						time: "执照上无经营期限则为长期有效"
					},
					{
						name: '固定有效期',
						time: "请选择营业执照截止日期"
					}
				],
				// 执照有效期标识
				licenseIndex: undefined,
				// 公司类型
				isLegalList: [{
						name: '机构',
						value: 1
					},
					{
						name: '个人',
						value: 0
					}
				],
				calendar: {
					maxDate: '',
					minDate: '',
					monthNum: '',
				},
				// 有效期时间的初始时间和结束时间
				startDate: new Date('1900-01-01'),
				endDate: new Date(),
				legalValidity: [], // 有效期时间组件的v-mode值

			}
		},
		onLoad() {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			this.getBasic()
		},
		methods: {
			// 修改有效期时间
			formatDate(date) {
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${year}-${month}-${day}`;
			},
			// 获取日历信息
			confirm(e) {

				this.merchantData.legalValidity = e[0] + '-' + e[e.length - 1]

				this.licenseArray[this.licenseIndex].time = e[0] + '-' + e[e.length - 1]
			},
			// 获取是否可以去编辑页面的值
			handleData(data) {
				this.echoShow = data
			},
			// 更新的点击事件
			updateClick() {
				this.$refs.licenseForm.validate().then(async res => {
					if (!this.merchantData.qualificationPicture) return this.$util.Tips({
						title: '请上传营业执照'
					});
					if (!(this.merchantData.legalValidity && this.merchantData.legalValidity)) return this
						.$util
						.Tips({
							title: '请您选择执照有效期'
						});
					let regex = /^(?:https?:\/\/)?[^/]+\/([^/]+)/;
					this.merchantData.qualificationPicture = this.licenseImage.replace(regex, "$1")
					uni.showModal({
						title: '提示',
						content: '确认更新吗？',
						showCancel: true,
						confirmText: '确定',
						success: async (res) => {
							if (res.confirm) {
								await this.basicUpdate()
							} else if (res.cancel) {
								this.$util.Tips({
									title: '已取消操作'
								})
							}
						}
					});

				}).catch(err => {
					uni.$u.toast('请您正确填写信息')
					console.log(err)
				})
			},
			// 公司类型搜索
			isLegalListSelect(e) {
				this.merchantData.isLegalName = e.name
				this.merchantData.isLegal = e.value
				this.$refs.licenseForm.validateField('isLegalName')
			},
			// 执照有效期选择
			licenseClick(index, item) {
				if (index == 0) {
					this.licenseArray[this.licenseIndex].time = "请选择营业执照截止日期"
				}
				this.licenseIndex = index
				this.merchantData.legalValidityType = index + 1
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					if (result == null) {
						uni.showToast({
							title: "上传失败",
							icon: "none",
						})
						this.deletePic(event.index, 1);
						break;
					}
					let newStatus = {
						status: 'success',
						message: '上传成功',
						url: result,
					}
					this.licenseImage = result

					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, newStatus))
					fileListLen++
					this.fileList3 = []
				}
			},
			uploadFilePromise(filePath) {
				return this.$util.uploadFilePromise(filePath, {
					url: 'upload/image',
					name: "multipart", //固定 multipart
					model: "product", //模块 用户user,商品product,微信wechat,news文章
					pid: 1, //分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列
					count: 1
				});
				// 修改商户入驻申请信息

			},
			async basicUpdate() {
				uni.showLoading({
					title: '加载中',
					mask: true,
				})
				try {
					let result = await basicUpdateApi(this.merchantData)
					uni.navigateBack(1);
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
					console.log(e)
					this.$util.Tips({
						title: e,
					})
				}
			},


			// 获取商户入驻信息回显
			async getBasic() {
				try {
					let result = await getBasicApi()
					if (result.code == 200) {
						if (result.data != null) {
							let data = result.data
							this.echoShow = true
							this.merchantData = data
							if (data.legalValidityType == 1) { // 执照
								this.licenseIndex = 0

							}
							if (data.legalValidityType == 2) { // 执照
								this.licenseIndex = 1
								this.licenseArray[this.licenseIndex].time = data.legalValidity
							}
							// 公司类型
							for (let i = 0; i < this.isLegalList.length; i++) {
								if (this.isLegalList[i].value == data.isLegal) {
									this.merchantData.isLegalName = this.isLegalList[i].name
									break;
								}
							}
							this.licenseImage = this.merchantData.qualificationPicture // 回显营业执照


						}


					}
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
			},


		},

	}
</script>

<style lang="scss" scoped>
	::v-deep .u-form-item__body__right__content__slot {
		justify-content: center;
	}

	page {
		display: flex;
		flex-direction: column;
		overflow: hidden;
		height: 100%;

		.container {
			display: flex;
			flex-direction: column;
			height: 100%;
		}
	}


	page {
		height: 100%;
	}

	.bg_color {
		@include main_bg_color(theme);

	}


	.text_color {
		@include main_color(theme)
	}

	.selectStyle {
		@include main_color(theme);
		@include border_color(theme);
		border: 1rpx solid;
	}

	.bottomStyle {
		position: sticky !important;
		;
		bottom: 0px !important;
		left: 0px !important;
	}




	.scrollHeight {
		flex: 1;
		min-height: 200px;
	}

	.one {
		display: flex;
		flex-direction: column;
		height: 100%;

		.BH5 {
			background-color: #F3F5F4;
			height: 4px;
		}

		.title {
			padding: 5px 0 15px;
			font-weight: 600;

			span {
				color: #E74949;
				padding-right: 5px;
			}
		}

		.position {
			display: flex;
			justify-content: space-between;
			padding: 5px 0 0;

			input {
				text-align: right;
			}
		}

		.bian {
			border-bottom: 1px solid #F7F7F7;
			background-color: white;
			padding: 10px 10px 20px;
			border-radius: 10px;

			.indate {
				display: flex;
				justify-content: space-around;
				padding: 20px 0;

				.header {
					width: 100px;
				}

				.indateList {
					display: flex;

					.indateItem {
						background-color: #eee;
						padding: 10px;
						line-height: 20px;
						width: 120px;
						padding-left: 10px;
						border-radius: 10px;
						margin-right: 10px;
					}
				}



			}
		}

		.shangc {
			display: flex;
			justify-content: center;
			padding: 20px 0;

			.sc-l {
				width: 48%;
				// text-align: center;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				color: #A1A1A1;

				.sc-l-img {
					padding: 10px 0;

					img {
						width: 140px;
						height: 85px;
					}
				}
			}
		}

		.yyzz {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 15px;


			img {
				width: 160px;
				height: 100px;
			}
		}

		.H50 {
			height: 50px;
		}

		.btn {
			position: fixed;
			bottom: 0;
			left: 0;
			padding: 10px;
			width: 100%;
			background-color: #fff;
			z-index: 9;
		}
	}
</style>